package chat.ui;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.border.BevelBorder;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.SoftBevelBorder;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreePath;

import chat.client.ClientMain;
import chat.client.ClientRequestor;
import chat.user.Message;
import chat.user.MessageCreator;
import chat.user.User;

import java.awt.HeadlessException;
import java.awt.ScrollPane;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;

public class GroupChatWindow extends JFrame {
		
	private static JTree groupTree;
	private JButton add_btn, remv_btn, refresh_btn, connect_btn;
	private int BUTTON_WIDTH=132;
	int i=385;
	private ChatPanel chat_panel;
	//private ClientRequestor client;
	public String username;
	private User user = new User();
	private JLabel usernameL;
	
	public GroupChatWindow() throws Exception{
	
		new MessageCreator(user);
		
		Random r = new Random();
		int num = r.nextInt(100);
		user.setUserName(Integer.toString(num));
		
		setVisible(true);
		setLayout(null);
		
		JPanel pt = new JPanel();
		JLabel label = new JLabel("This is a default screen");
		
		/*pt.setLayout(null);
		pt.add(label);
		label.setBounds(50, 0, 150, 150);
		pt.setBounds(300, 0, 200,200);*/
	
		setBounds(0,0,100,100);
		JPanel p = new JPanel();
		p.setLayout(null);
		add(p);
		
		usernameL = new JLabel(user.getUserName());
		p.add(usernameL);
		usernameL.setVisible(true);
		usernameL.setBounds(0, 300, 100, 70);
		
		chat_panel = new ChatPanel(user);
		this.add(chat_panel);
		chat_panel.setVisible(true);
		this.chat_panel.setBounds(245, 0, 400,400);
		
		
		refresh_btn = new JButton("Refresh Groups");
		refresh_btn.setBounds(130, 200, 100, 70);
		
		//p.add(refresh_btn);
		
		connect_btn = new JButton("Connect to Group");
		connect_btn.setBounds(0, 260, BUTTON_WIDTH, 30);
		connect_btn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e){
				
				displayChatWindow ();
				MessageCreator.ConnectGroupRequest(getSelectedGroupName(), user);
			}
		});
		p.add(connect_btn);
		
		
		add_btn = new JButton("Add New Group");
		add_btn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e){
				
				requestNewGroup();
			}
		});
		add_btn.setBounds(0, 200, BUTTON_WIDTH, 30);		
		
		remv_btn = new JButton("Remove Group");
		remv_btn.setEnabled(false);
		remv_btn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e){
				
				removeItem();
			}
		});
		remv_btn.setBounds(0, 230, BUTTON_WIDTH, 30);
		p.add(remv_btn);
		
		DefaultMutableTreeNode top = new DefaultMutableTreeNode("ROOT");
		groupTree = new JTree(top);
		p.add(add_btn);
		
		
		JScrollPane sc = new JScrollPane(groupTree);
		sc.setBounds(0, 0, 235, 200);
		p.add(sc);
		
		p.setBounds(0, 0, 250, 400);
		
		groupTree.addTreeSelectionListener(new TreeSelectionListener() {
			
			@Override
	public void valueChanged(TreeSelectionEvent arg0) {
				
				Object obj = groupTree.getLastSelectedPathComponent();
				DefaultMutableTreeNode node = (DefaultMutableTreeNode)obj;
				
				if (node != null){
				
					if (!node.isRoot()){
					
							add_btn.setEnabled(false);
							remv_btn.setEnabled(true);
					}
				
					if (node.isRoot()){
					
						add_btn.setEnabled(true);
						remv_btn.setEnabled(false);
					}
				}
			}
		});
		
		add(pt);
		
		MessageCreator.AuthRequest(user);
		
		new Thread (new ClientMain(this)).start();
		
		setBounds(800,200,600,385);
	}
	
	 public void requestNewGroup()
	    {
	        
	        DefaultTreeModel model = (DefaultTreeModel) groupTree.getModel();
	        Object obj = groupTree.getLastSelectedPathComponent();
	        DefaultMutableTreeNode root = (DefaultMutableTreeNode)model.getRoot();
	        int nodes_count = groupTree.getRowCount();
	        
	      /*  if(obj!=null)
	        {
	            DefaultMutableTreeNode sel = (DefaultMutableTreeNode)obj;
	         
	            //Adding more deeper branches 
	            
	           /* if(sel.getLevel()>=1) {
	                DefaultMutableTreeNode tmp = new DefaultMutableTreeNode("Deep");
	                model.insertNodeInto(tmp, sel, sel.getChildCount());
	            }*/
	            
	           // if(sel.isRoot()) {
	            	
	            	String ask = JOptionPane.showInputDialog("Enter group name");
	            	
	            	boolean isGroupAlreadyExist=false;
	            	
	            	if (ask != null){
	                
	            		if (nodes_count>1){
	            		
	            			for (int i=0; i<nodes_count-1; i++){
	            			
	            				String node_name = model.getChild(root, i).toString();
	            				
	            				if (ask.equalsIgnoreCase(node_name)){
	            					
	            					isGroupAlreadyExist = true;
	            				}
	            			}
	            			if (!isGroupAlreadyExist){
	            				
	            				DefaultMutableTreeNode tmp = new DefaultMutableTreeNode(ask);
           		             //	model.insertNodeInto(tmp, root, model.getChildCount(root));
           		             	
           		             	MessageCreator.RequestNewGroup(ask, user);
           		             	
           		             	isGroupAlreadyExist = false;
	            			}
	            			else {
	            				
	            				final ImageIcon icon = new ImageIcon("red1.jpg");
	            				JOptionPane.showMessageDialog(null, "Group is already exist","Error",JOptionPane.INFORMATION_MESSAGE, icon);
	            			}
	            		}
	            		else {
	            			
	            			DefaultMutableTreeNode tmp = new DefaultMutableTreeNode(ask);
	            			//model.insertNodeInto(tmp, root, model.getChildCount(root));
	            			
	            			MessageCreator.RequestNewGroup(ask, user);
	            		} 
	            	}
	           // }
	          //  groupTree.expandPath(new TreePath(sel.getPath()));
	        }
	    //}
	 
	 public void addNewItem(String name)
	    {
	        
	        DefaultTreeModel model = (DefaultTreeModel) groupTree.getModel();
	        DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
	        
	        int nodes_count = groupTree.getRowCount();
         	boolean isGroupAlreadyExist=false;
         	
         	if (nodes_count>1){
        		
    			for (int i=0; i<nodes_count-1; i++){
    			
    				String node_name = model.getChild(root, i).toString();
    				
    				if (name.equalsIgnoreCase(node_name)){
    					
    					isGroupAlreadyExist = true;
    				}
    			}
    			if (!isGroupAlreadyExist){
    				
    					DefaultMutableTreeNode tmp = new DefaultMutableTreeNode(name);
    					model.insertNodeInto(tmp, root, (model.getChildCount(root)));
		             	
		             	//client.RequestNewGroup(name);
		             	
		             	isGroupAlreadyExist = false;
    			}
    			
    		}
    		else {
    			
    				DefaultMutableTreeNode tmp = new DefaultMutableTreeNode(name);
    				model.insertNodeInto(tmp, root, (model.getChildCount(root)));
    			
    		} 
         	
         	model.reload(root);
	        
	    }
	 
	 public void removeItem()
	    {
	        DefaultTreeModel model = (DefaultTreeModel)groupTree.getModel();
	        Object obj = groupTree.getLastSelectedPathComponent();
	        if(obj!=null)
	        {
	            DefaultMutableTreeNode sel = (DefaultMutableTreeNode)obj;
	            
	            if(!sel.isRoot())
	            {
	                if(sel.getChildCount()==0){
	                	
	                	groupTree.setFocusable(false);
	                	model.removeNodeFromParent(sel);
	                	
	                }
	                    
	                else
	                    
	                    JOptionPane.showMessageDialog(null, "Remove all subnodes");
	            }
	        }
	    }
	 
	 public void displayChatWindow(){
		 
		 chat_panel.setVisible(true);
		
	 }
	 
	 public ChatPanel getChat(){
		 return chat_panel;
	 }
	 
	 public User getUser(){
		 return this.user;
	 }
	 
	 public void setUser(User u){
		 
		 this.user = u;
	 }
	 
	 public String getSelectedGroupName(){
		 
		 DefaultTreeModel model = (DefaultTreeModel) groupTree.getModel();
	     Object obj = groupTree.getLastSelectedPathComponent();
	     String node_name = obj.toString();
	        
		 return node_name;
	 }
}